package com.example.silvercare;

import java.util.Scanner;
import java.util.StringTokenizer;

public class UserInputCheck {
	
	//return 0 means OK
	//Don't allow input '|'
	static public boolean checkUserInput(String input)
	{	
		//either invalid or null
		if(input == "" || input == null)
			return false;
		if(input.contains("|"))
			return false;
		return true;
	}
	
	//remove space at the beginning and end of string
	static public String removeBlankSpace(String input)
	{
		String result = "";

		StringTokenizer st = new StringTokenizer(input," ",false);
		result="";
		boolean zero = true;
		while (st.hasMoreElements()) 
		{
			String t = (String) st.nextElement();
			if(t!= null && !t.equalsIgnoreCase(""))
			{
				if(zero)
				{
					result += t;
					zero = false;
				}
				else
					result += " "+t;
			}
			//result += st.nextElement();
		}

		return result;
	}
	
	//return small case of input string
	static public String toSmallCase(String input)
	{
			return input.toLowerCase();
	}
	
	static public String nameCheck(String inputName)
	{
		String result = null;
		
		//remove blank space
		result = removeBlankSpace(inputName);
		
		//check '|'
		if(checkUserInput(result))
			return result;
		else
			return null;
	}
	
	static public String emailaddressCheck(String inputEmail){
		String result = null;
		
		//remove blank space
		result = removeBlankSpace(inputEmail);
		
		//change to small case
		result = toSmallCase(result);
		
		//check '|'
		if(checkUserInput(result))
			return result;
		else
			return null;
	}
	
	static public String addressCheck(String inputAddress){

		String result = "";
		
		//separate by ';'
        Scanner sc=new Scanner(inputAddress).useDelimiter("\\;");
		String s;
		boolean zero = true;
		while(sc.hasNext())
		{
			s = sc.next();
			s = removeBlankSpace(s);
			if(s!=null && !s.equalsIgnoreCase(""))
			{
				if(zero)
				{
					result += s;
					zero = false;
				}
				else
				{
					result += ";"+s;
				}
			}
		}

		//check '|'
		if(checkUserInput(result))
			return result;
		else
			return null;
	}
	
	static public boolean timeCheck(String inputTime){
		
		if(inputTime == null || inputTime == "")
			return false;
		// no space
		if(inputTime.indexOf(" ")!=-1)
			return false;
		
		//separate by ';'
        Scanner sc=new Scanner(inputTime).useDelimiter("\\;");
        while(sc.hasNext())
        {
        	String s = sc.next();
        	String s1, s2;
        	int mid = s.indexOf(":");
        	if(mid==-1)
        		return false;
        	s1 = s.substring(0, mid);
        	s2 = s.substring(mid+1, s.length());
        	System.out.println("s1 :" + s1);
        	System.out.println("s2 :" + s2);
        	if(s1 == null || s2 == null)
        		return false;
        	int hour = Integer.parseInt(s1);
        	int minute = Integer.parseInt(s2);
        	if(hour < 0 || hour > 23 || minute <0 || minute > 59)
        		return false;
        }
		return true;
	}
}
